<template>
  <div>
    <h1>注册</h1>
    <p>
      <input type="text" placeholder="用户名" v-model="username" />
    </p>
    <p>
      <input type="password" placeholder="密码" v-model="password" />
    </p>
    <p>
      <input type="password" placeholder="确认密码" v-model="rePassword" />
    </p>
    <p>
      <router-link to="/login">登陆</router-link>
    </p>
    <p>
      <button @click="submitRegister">注册</button>
    </p>
  </div>
</template>

<script setup lang="ts">
import { useRegister } from './hooks/user';
import { useRouter } from 'vue-router';
import errorHandler from '../config/errorHandler';

const router = useRouter();
const {
  username,
  password,
  rePassword,
  checkUserInfo,
  submitUserInfo,
  comparePassword,
} = useRegister();

const submitRegister = async () => {
  //当用户名长度小于6位时
  if (!checkUserInfo(username, 6)) {
    alert('用户名长度不小于6位');
    return;
  }
  //当密码长度小于6位时
  if (!checkUserInfo(password, 6)) {
    alert('密码长度不小于6位');
    return;
  }
  //当密码和确认密码不一致时
  if (!comparePassword()) {
    alert('密码和确认密码不一致');
    return;
  }
  try {
    const { err_code } = await submitUserInfo();
    //err_code !== 0 时 说明失败
    if (err_code) {
      alert(errorHandler[err_code]);
      return;
    }
    //跳转至登陆页面
    router.push('/login');
  } catch (e) {
    alert('注册失败');
  }
};
</script>

